package com.core.hibernate;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.core.hibernate.exceptionevent.ExceptionEvent;
import com.core.protocols.IExceptionListener;


public class ExceptionHandler {

	private static ExceptionHandler                    Instance  = null;
	private Map <String, HashSet <IExceptionListener>> listeners = new HashMap <String, HashSet <IExceptionListener>>();



	public static void handleException ( Exception e,
	                                     ExceptionEvent event ) {

		ExceptionHandler handler = ExceptionHandler.sharedInstance();

		handler.logException(e, event);
	}



	public void addListener ( IExceptionListener exceptionListener,
	                          Set <ExceptionEvent> events ) {

		if ( events == null ) {
			return;
		}

		Iterator <ExceptionEvent> iterator = events.iterator();

		while ( iterator.hasNext() ) {
			ExceptionEvent event = iterator.next();

			if ( !listeners.containsKey(event) ) {
				listeners.put(event.getEventName(), new HashSet <IExceptionListener>());
			}
			Set <IExceptionListener> objects = listeners.get(event.getEventName());
			objects.add(exceptionListener);
		}
	}



	public void removeListener ( IExceptionListener exceptionListener,
	                             Set <ExceptionEvent> events ) {

		if ( events == null ) {
			return;
		}

		Iterator <ExceptionEvent> iterator = events.iterator();

		while ( iterator.hasNext() ) {
			ExceptionEvent event = iterator.next();
			Set <IExceptionListener> objects = listeners.get(event);
			if ( objects == null ) {
				continue;
			}
			objects.remove(exceptionListener);
		}
	}



	public static ExceptionHandler sharedInstance () {

		if ( Instance == null ) {

			Instance = new ExceptionHandler();
			if ( Instance != null ) {

			}

		}
		return Instance;
	}



	public void logException ( Exception e,
	                           ExceptionEvent event ) {

		if ( event == null ) {
			return;
		}
		Set <IExceptionListener> objects = listeners.get(event.getEventName());
		if ( objects == null ) {
			return;
		}

		Iterator <IExceptionListener> iterator = objects.iterator();

		while ( iterator.hasNext() ) {
			IExceptionListener listener = iterator.next();
			listener.parseException(e);
		}

		// System.out.println(e.fillInStackTrace());
	}



}
